import ora from "ora";
import fs from "fs";
import { runCmd, runCmdSync } from "../utils/runCmd.js";
import createQuestions from "../questions/createQuestions.js";
import cloneGitRemoteFileAndWrite from "../utils/cloneGitRemoteFileAndWrite.js";
import reactPackageJson from "../template/react.package.json/index.js";
import jsPackageJson from "../template/js.package.json/index.js";
import chalk from "chalk";

// 根据框架获取 package.json 内容
const getPackageJson = (createConfig) => {
  switch (createConfig.framework) {
    case "vue":
      return reactPackageJson(createConfig);
    case "react":
      return reactPackageJson(createConfig);
    case "js":
      return jsPackageJson(createConfig);
  }
};

export default async (projectName) => {
  let createConfig = await createQuestions();
  createConfig.projectName = projectName;
  const createSpinner = ora(chalk.hex('#977f55')("开始创建..."));
  createSpinner.start();

  // 克隆远程仓库读取文件并写入项目
  await cloneGitRemoteFileAndWrite(createConfig);

  // 写入package.json
  fs.writeFileSync(
    `${createConfig.projectName}/package.json`,
    getPackageJson(createConfig),
    { encoding: "utf8" }
  );

  // 安装依赖
  runCmd("git", ["init"], {
    cwd: createConfig.projectName,
  });

  console.log(chalk.green("安装依赖..."));

  // 安装依赖
  console.log(`${createConfig.installTool} install`);
  runCmdSync(createConfig.installTool, ["install"], {
    cwd: createConfig.projectName,
  });

  // 安装 package-cli-service TODO 开发环境使用
  // const install = createConfig.installTool === "yarn" ? "add" : "install";
  // console.log(
  //   `${createConfig.installTool} ${install} -D package-cli-service@alpha`
  // );
  // runCmdSync(
  //   createConfig.installTool,
  //   [install, "-D", "package-cli-service@alpha"],
  //   {
  //     cwd: createConfig.projectName,
  //   }
  // );

  // 启用 Git hooks
  console.log("npx husky install");
  runCmdSync("npx", ["husky", "install"], {
    cwd: createConfig.projectName,
  });

  // 创建 commit-msg hook
  console.log(
    "npx husky add .husky/commit-msg 'npx --no -- commitlint --edit \"$1\"'"
  );
  runCmdSync(
    "npx",
    ["husky", "add", ".husky/commit-msg", 'npx --no -- commitlint --edit "$1"'],
    {
      cwd: createConfig.projectName,
    }
  );

  // git add
  console.log("git add --all");
  runCmdSync("git", ["add", "--all"], {
    cwd: createConfig.projectName,
  });

  // git commit
  console.log('git commit -m "build: init"');
  runCmdSync("git", ["commit", "-m", "build: init"], {
    cwd: createConfig.projectName,
    stdio: 'pipe'
  });

  createSpinner.succeed(`成功创建 package ${chalk.hex('#ffd700')(createConfig.projectName)}`);
  console.log(`从以下命令开始：`);
  console.log(`$ ${chalk.hex('#287F8C')(`cd ${createConfig.projectName}`)}`);
  console.log(`$ ${chalk.hex('#287F8C')("npm run serve-example")}`);
};
